/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package businesscard.DAO;

import bc.entity.Bophan;
import bc.util.HibernateUtil;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author Welcome
 */
public class BophanDAO {

    private Session session;

    public BophanDAO() {
        SessionFactory factory = HibernateUtil.getSessionFactory();
        this.session = factory.getCurrentSession();
    }

    public Bophan[] getAllBophan() {
        try {
            session.getTransaction().begin();
            String sql = "from Bophan";
            Query query = session.createQuery(sql);
            List result = query.list();
            Bophan[] bophanList = new Bophan[result.size()];
            result.toArray(bophanList);
            session.flush();
            session.getTransaction().commit();
            return bophanList;
        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        return null;

    }

    // cuanga
    public Bophan getBophanById(int id) {
        session.beginTransaction().begin();
        String sql = "from Bophan where idbophan=?";
        try {
            Query query = session.createQuery(sql);
            query.setInteger(0, id);
            Bophan bp = (Bophan) query.uniqueResult();
            session.flush();
            return bp;

        } catch (Exception e) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            e.printStackTrace();
        }
        return null;
    }
    public List<Bophan> getBophanLikeName(String name){
        session.beginTransaction().begin();
        String sql = "from Bophan where bophan like ?";
        try {
            Query query = session.createQuery(sql);
            query.setString(0, "%" + name + "%");
            List result = query.list();
          //  Bophan[] arrbp = new Bophan[result.size()];
          //  result.toArray(arrbp);
            session.flush();
            //session.getTransaction().commit();
            return result;
        } catch (Exception ex) {
            if (session.getTransaction().isActive()) {
                session.getTransaction().rollback();
            }
            ex.printStackTrace();
        }
        return null;
    }
}
